<?php namespace App\Http\Controllers\Api\Admin;

use App\Admin;
use App\AdvertImg;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\ChargeAvailable;
use App\ChargeRecord;
use App\Classify;
use App\Coupons;
use App\DiscountRule;
use App\DiscountSalesRule;
use App\Express;
use App\ExpressBlade;
use App\ExpressCustomFee;
use App\GoodsServiceLabel;
use App\Http\Controllers\Controller;
use App\Http\Services\BusinessLicense;
use App\Http\Services\FileManager;
use App\RechargePackage;
use App\ReturnAddress;
use App\Shops;
use App\ShowGoods;
use App\User;
use App\UserInfo;
use App\VipRule;
use Auth;
use Illuminate\Http\Request;
use DB;
use Log;

class SystemController extends Controller
{
    public function setBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId(trim($id))->first();

        if(!$thatBanner)
            $thatBanner = new Banner();

        if(!is_null($title))$thatBanner->title = $title;
        if(!is_null($linkUrl))$thatBanner->link_url = $linkUrl;
        if(!is_null($sort))$thatBanner->sort = $sort;
        if(!is_null($imgId))$thatBanner->img_id = $imgId;
        if(!is_null($imgId))$thatBanner->status = 1;
        $thatBanner->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatBanner]);
    }
    public function delBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();

        if(!$thatBanner)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBanner]);
    }
    public function setAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $username = $request->get('username');
        $password = $request->get('password');
        $repass   = $request->get('repass');

        if($password != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        /** @var Admin $hasUser */
        $hasUser = Admin::whereUsername($username)->first();
        if($hasUser){
            return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);
        }

        $thatAdmin = new Admin();
        $thatAdmin->username = $username;
        $thatAdmin->password = bcrypt($password);
        $thatAdmin->status = 2;
        $thatAdmin->save();

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatAdmin]);
    }
    public function delAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatAdmin = Admin::whereId($id)->first();

        if(!$thatAdmin)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatAdmin->status == 1)
            return response()->json(["level"=>"error","message"=>"该管理员不能删除！"]);


        $thatAdmin->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatAdmin]);
    }

    public function addClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name                      = $request->get("name");
        $pId                       = $request->get("pid");
        $sort                      = $request->get('sort');
        $linkUrl                   = $request->get('link_url');
        $imgId                     = $request->get('img_id');
        $type                      = $request->get('type');
        $classifyId                = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $classifyTwoId             = !is_null($request->get('classify_two_id')) ? $request->get('classify_two_id') : 0;
        $homeShow    = $request->get("home_show");
        $advertImgId = $request->get("advert_img_id");
        $id                        = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Classify $newClassify */
        $newClassify = Classify::whereId(trim($id))->first();

        if(!$newClassify)
            $newClassify = new Classify();

        if(!is_null($pId))$newClassify->pid                       = $pId;
        if(!is_null($name))$newClassify->name                     = $name;
        if(!is_null($sort))$newClassify->sort                     = $sort;
        if(!is_null($linkUrl))$newClassify->link_url              = $linkUrl;
        if(!is_null($imgId))$newClassify->img_id                  = $imgId;
        if(!is_null($homeShow))$newClassify->home_show            = $homeShow;
        if(!is_null($advertImgId))$newClassify->advert_img_id     = $advertImgId;
        if($classifyId != 0)$newClassify->classify_id             = $classifyId;
        if($classifyTwoId != 0)$newClassify->classify_id          = $classifyTwoId;
        $newClassify->type                           = $type;
        $newClassify->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$newClassify]);
    }

    public function delClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;
        $thatClassify =Classify::whereId($id)->first();

        if(!$thatClassify)
            return response()->json(["level"=>"error","message"=>"该分类不存在！"]);

        $thatClassify->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function setGoodsServiceLabel(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name                      = $request->get("name");
        $sort                      = $request->get('sort');
        $id                        = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var GoodsServiceLabel $newGoodsServiceLabel */
        $newGoodsServiceLabel = GoodsServiceLabel::whereId(trim($id))->first();

        if(!$newGoodsServiceLabel)
            $newGoodsServiceLabel = new GoodsServiceLabel();

        if(!is_null($name))$newGoodsServiceLabel->name                     = $name;
        if(!is_null($sort))$newGoodsServiceLabel->sort                     = $sort;
        $newGoodsServiceLabel->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$newGoodsServiceLabel]);
    }

    public function delGoodsServiceLabel(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatGoodsServiceLabel =GoodsServiceLabel::whereId($id)->first();
        if(!$thatGoodsServiceLabel)
            return response()->json(["level"=>"error","message"=>"该标签不存在！"]);

        $thatGoodsServiceLabel->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function getChildClassify(Request $request){

        $id = $request->get('id');

        /** @var Classify $thatClassify */
        $thatClassify = Classify::whereId($id)->first();

        if(!$thatClassify)
            return response()->json(["level"=>"error","message"=>"未找到该分类"],203);

        $childClassify = Classify::wherePid($thatClassify->id)->get();

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$childClassify]);
    }

    public function setExpressCompany(Request $request){

        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id=!is_null($request->get('id'))?$request->get('id'):0;
        $name=$request->get('name');
        $fee=$request->get('fee');
        $orderFreeShippingPrice    = $request->get('order_free_shipping_price');
        $order_free_shipping_num   = $request->get('order_free_shipping_num');

        $thatExpressCompany=Express::whereId($id)->first();

        if(!$thatExpressCompany)
            $thatExpressCompany=new Express();

        if(!is_null($name))$thatExpressCompany->name = $name;
        if(!is_null($fee))$thatExpressCompany->fee=$fee;
        if(!is_null($orderFreeShippingPrice))$thatExpressCompany->order_free_shipping_price = $orderFreeShippingPrice;
        if($order_free_shipping_num) $thatExpressCompany->order_free_shipping_num = $order_free_shipping_num;
        $thatExpressCompany->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatExpressCompany]);
    }

    public function delExpressCompany(Request $request){

        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))? $request->get('id'):0;

        $thatExpressCompany=Express::whereId($id)->first();

        if(!$thatExpressCompany)

            return response()->json(["level"=>"error","message"=>"该快递公司不存在！"]);

        $thatExpressCompany->delete();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatExpressCompany]);

    }

    public function setExpressUse(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $id = $request->get("id");

        $allExpress=Express::orderBy('created_at','desc')->get();

        if(count($allExpress)>0){
            foreach ($allExpress  as $express){
                $express->is_default=0;
                $express->save();
            }

        }

        $thisExpress=Express::whereId($id)->first();
        if(!$thisExpress)
            return response()->json(["level"=>"error","message"=>"快递公司不存在！"]);

        /*     if($thisExpress->is_default == 1){
                 $thisExpress->is_default = 0;
                 $thisExpress->save();
             }else{
                 $thisExpress->is_default = 1;
                 $thisExpress->save();
             }*/

        $thisExpress->is_default=1;
        $thisExpress->save();
        return response()->json(["level"=>"success","message"=>"启用成功","data"=>$thisExpress]);
    }

    public function setCoupons(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $remark         =$request->request->get('remark');
        $name           = $request->get('name');
        $money          = $request->get('money');
        $startTime      = $request->get('start_time');
        $endTime        = $request->get('end_time');
        $type           = $request->get('type');
        $satisfyMoney   = $request->get('satisfy_money');
        $num            = $request->get('num');
        $status         = $request->get('status');
        $imgId          = $request->get('imgId');
        $id             = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newCoupon = Coupons::whereId($id)->first();
        if(!$newCoupon)
            $newCoupon = new Coupons();

        if(!is_null($name))$newCoupon->name                        = $name;
        if(!is_null($money))$newCoupon->money                      = $money;
        if(!is_null($startTime))$newCoupon->start_time             = $startTime;
        if(!is_null($endTime))$newCoupon->end_time                 = $endTime;
        if(!is_null($type))$newCoupon->type                        = $type;
        if(!is_null($satisfyMoney))$newCoupon->satisfy_money       = $satisfyMoney;
        if(!is_null($num))$newCoupon->num                          = $num;
        if(!is_null($status))$newCoupon->status                    = $status;
        if(!is_null($remark))$newCoupon->remark                    =$remark;
        if(!is_null($imgId))$newCoupon->img_id                    =$imgId;
        $newCoupon->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newCoupon]);
    }

    public function delCoupons(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thatCoupon = Coupons::whereId($id)->first();
        if(!$thatCoupon)
            return response()->json(['level' => 'error','message' => '该优惠群不存在']);

        $thatCoupon->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatCoupon]);
    }

    //下面是新写的
    public function getUserList(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $keyword= !is_null($request->get('keyword'))     ? $request->get('keyword')  : '';
        $page   = !is_null($request->get('page'))   ? $request->get('page')     : 1;
        $limit  = !is_null($request->get('limit'))  ? $request->get('limit')    : 10;
        $page_info=[
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page=$page-1;
        $user=User::whereRole(1)->orderBy('created_at','desc');
        if ($keyword){
            $user_Ids=UserInfo::where('nickname','like','%'.trim($keyword).'%')
            ->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $user=$user->whereIn('id',$user_Ids)->orWhere('phone','like','%'.trim($keyword).'%');
        }
        $page_info['total']=$user->count();
        $user=$user->offset($page * $limit)->limit($limit)->get();
        $result=[];
        if (count($user) > 0){
            /** @var User $item */
            foreach ($user as $item){
                $temp=[];
                $user_info=$item->userInfo;
                $temp['id']             =$item->id;
                $temp['head_img_url']   =FileManager::getImgUrl($user_info->photo_id);
                $temp['nickname']       =$user_info->nickname;
                $temp['sex']            =$user_info->sex;
                $temp['phone']          =$item->phone;

                array_push($result,$temp);
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result]);

    }

    public function setAdvertImg(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $type    = $request->get('type');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatAdvertImg = AdvertImg::whereId($id)->first();
        if(!$thatAdvertImg)
            $thatAdvertImg = new AdvertImg();

        if(!is_null($title))$thatAdvertImg->title      = $title;
        if(!is_null($linkUrl))$thatAdvertImg->link_url = $linkUrl;
        if(!is_null($sort))$thatAdvertImg->sort        = $sort;
        if(!is_null($type))$thatAdvertImg->type        = $type;
        if(!is_null($imgId))$thatAdvertImg->img_id     = $imgId;
        $thatAdvertImg->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatAdvertImg]);
    }

    public function delAdvertImg(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatAdvertImg = AdvertImg::whereId($id)->first();
        if(!$thatAdvertImg)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatAdvertImg->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatAdvertImg]);
    }

    public function addChargeRecord(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $user_id=$request->get('user_id');
        $amount=$request->get('amount');
        $remark=$request->get('remark');
//        $discount_id=$request->get('discount_id');
        if (!$user_id)
            return response()->json(["level"=>"error","message"=>"参数错误"]);
        if (!is_numeric($amount) || !$amount)
            return response()->json(["level"=>"error","message"=>"请输入充值金额"]);
        $is_user=User::whereId($user_id)->first();
        if (!$is_user)
            return response()->json(["level"=>"error","message"=>"用户不存在"]);
        DB::beginTransaction();
        try {
            //新增充值记录
            $record = new ChargeRecord();
            $record->user_id = $is_user->id;
            if ($is_user->phone)
                $record->phone = $is_user->phone;
            $record->charge_money = round($amount, 2);
            $record->remark = $remark ? $remark :'';
            $record->save();

            //添加余额
            $available = ChargeAvailable::whereUserId($is_user->id)->first();
            if (!$available) {
                $available = new ChargeAvailable();
                $available->user_id = $is_user->id;
                $available->amount = $record->charge_money;

            } else {
                $available->amount = $available->amount + $record->charge_money;
            }
//            $available->discount_rule_id=$discount_id ? $discount_id : 0;
            $available->save();
        } catch (\Exception $exception){
            DB::rollback();
            Log::error('chargeERROR=>'.$exception->getMessage());
            return response()->json(['level'=>'error','message'=>'充值发生错误']);
        }
        DB::commit();
        return response()->json(['level'=>'success','message'=>'充值成功']);
    }
    public function setUserDiscount(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $user_id=$request->get('user_id');
//        $amount=$request->get('amount');
        $discount_id=$request->get('discount_id');
        if (!$user_id)
            return response()->json(["level"=>"error","message"=>"参数错误"]);

        $is_user=User::whereId($user_id)->first();
        if (!$is_user)
            return response()->json(["level"=>"error","message"=>"用户不存在"]);

        //修改折扣规则
        $available = ChargeAvailable::whereUserId($is_user->id)->first();
        if (!$available) {
            $available = new ChargeAvailable();
            $available->user_id = $is_user->id;
            $available->amount = 0;
        }
        $available->discount_rule_id=$discount_id ? $discount_id : 0;
        $available->save();
        return response()->json(['level'=>'success','message'=>'充值成功']);
    }

    public function addDiscountRule(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $rule_name  =$request->get('name');
        $rate       =$request->get('rate');
        $id         =$request->get('id');
        if (!$rule_name)
            return response()->json(["level"=>"error","message"=>"请输入规则名称"]);
        if (!is_numeric($rate))
            return response()->json(["level"=>"error","message"=>'请输入利率，保留2位小数']);
        if ($rate<=0 || $rate > 1)
            return response()->json(["level"=>"error","message"=>"利率取值范围是大于0，且小于等于1"]);

        $rule=DiscountRule::whereId($id)->first();
        if (!$rule)
            $rule= new DiscountRule();
        $rule->rate=$rate ? round($rate,2) : 1;
        $rule->rule_name=$rule_name;
        $rule->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }
    public function setDiscountSalesRule(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name=$request->get('name');
        $type=$request->get('type');
        $range=$request->get('range');
        $satisfy_number=$request->get('satisfy_number');
//        $satisfy_money=$request->get('satisfy_money');
        $free_get_number=$request->get('free_get_number');
        $reduce_amount=$request->get('reduce_amount');
        $reduce_rate=$request->get('reduce_rate');
        $start_time=$request->get('start_time');
        $end_time=$request->get('end_time');
        $status=$request->get('status');
        $id=$request->get('id');

        if (!$name)
            return response()->json(["level"=>"error","message"=>"请输入规则名称"]);

        if (!in_array($type,['buy_get_free','reduce','discount']))
            return response()->json(["level"=>"error","message"=>"请选择规则类型"]);
        if (!in_array($range,['vip','all']))
            return response()->json(["level"=>"error","message"=>"请选择适用范围"]);

        if (!is_numeric($satisfy_number))
            return response()->json(["level"=>"error","message"=>"请输入满足条件的数量"]);
        if ($satisfy_number < 1)
            return response()->json(["level"=>"error","message"=>"满的数量需要大于等于1"]);

        if ($type == 'buy_get_free'){
            if (!is_numeric($free_get_number))
                return response()->json(["level"=>"error","message"=>"请输入赠送的数量"]);
        }

        if ($type == 'reduce'){
            if (!is_numeric($reduce_amount))
                return response()->json(["level"=>"error","message"=>"请输入减掉的金额"]);
        }
        if ($type == 'discount'){
            if (!is_numeric($reduce_rate))
                return response()->json(["level"=>"error","message"=>"请输入优惠的折扣率"]);
            if ($reduce_rate<=0 || $reduce_rate > 1)
                return response()->json(["level"=>"error","message"=>"取值范围是大于0，且小于等于1"]);
        }
        $thisRule=DiscountSalesRule::whereId($id)->first();
        if (!$thisRule)
            $thisRule=new DiscountSalesRule();
        $thisRule->name=$name;
        $thisRule->type=$type;
        $thisRule->range=$range;
        $thisRule->satisfy_number   =$satisfy_number;
        $thisRule->status           =$status ? 1 : 0;

        if ($start_time)
            $thisRule->start_time   =$start_time;
        if ($end_time)
            $thisRule->end_time     =$end_time;
        if ($type == 'buy_get_free')
            $thisRule->free_get_number=$free_get_number;
        if ($type == 'reduce')
            $thisRule->reduce_amount=$reduce_amount;
        if ($type == 'discount')
            $thisRule->reduce_rate  =$reduce_rate;
        $thisRule->save();

        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    public function setExpressCustomFee(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $express_blade_id   =$request->get('express_blade_id');
        $first_weight       =$request->get('first_weight');
        $first_price        =$request->get('first_price');
        $next_weight        =$request->get('next_weight');
        $next_price         =$request->get('next_price');
        $province           =$request->get('province');
        $city           =$request->get('city');
        $id=$request->get('id');
        if (!$express_blade_id)
            return response()->json(['level'=>'error','message'=>'参数错误','data'=>[]]);
        if (!$next_weight)
            return response()->json(['level'=>'error','message'=>'续重需要大于0','data'=>[]]);

        if ($id){
            $thisCustomFee=ExpressCustomFee::whereId($id)->first();
            if (!$thisCustomFee)
                $thisCustomFee=new ExpressCustomFee();
        } else {
            $thisCustomFee=new ExpressCustomFee();
        }

        $thisCustomFee->express_blade_id=$express_blade_id  ? $express_blade_id : 0;
        $thisCustomFee->first_weight    =$first_weight      ? $first_weight : 0;
        $thisCustomFee->first_price     =$first_price       ? $first_price  : 0;
        $thisCustomFee->next_weight     =$next_weight       ? $next_weight  : 0;
        $thisCustomFee->next_price      =$next_price        ? $next_price   : 0;
        $thisCustomFee->province        =$province          ? $province     : '全国';
        $thisCustomFee->city        =$city          ? $city     : '全部';
        $thisCustomFee->save();
        return response()->json(['level'=>'success','message'=>'设置成功','data'=>$thisCustomFee]);
    }
    public function setExpressBlade(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name   =$request->get('name');
//        $status =$request->get('status');
//        $is_use =$request->get('is_use');
//        $sort   =$request->get('sort');
        $is_default =$request->get('is_default');

        $id     =$request->get('id');
        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入模板名称']);
        $exist=ExpressBlade::whereName($name)->first();

        $thisBlade=ExpressBlade::whereId($id)->first();
        if (!$thisBlade){
            $thisBlade=new ExpressBlade();
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);
        } else if ($exist){
            if ($thisBlade->id != $exist->id)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);
        }
        if ($is_default){
            $default_num=ExpressBlade::whereIsDefault(1)->count();
            if ($default_num)
                return response()->json(['level'=>'error','message'=>'只能有一个默认的哦']);
        }

        $thisBlade->name    = $name   ? $name   : '';
        $thisBlade->is_default  = $is_default ? $is_default : 0;
//        $thisBlade->sort    = $sort   ? $sort   : 1;
//        $thisBlade->status  = $status ? $status : 0;
//        $thisBlade->is_use  = $is_use ? $is_use : 0;
        $thisBlade->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$thisBlade]);
    }
    public function delExpressCustomFee(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $id=$request->get('id');
        $thisRecord=ExpressCustomFee::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error','message'=>'该记录不存在','data'=>[]]);
        $thisRecord->delete();
        return response()->json(['level'=>'success','message'=>'删除成功','data'=>[]]);
    }
    public function delExpressBlade(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $id=$request->get('id');
        $thisRecord=ExpressBlade::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error','message'=>'该记录不存在','data'=>[]]);
        $thisRecord->delete();
        ExpressCustomFee::whereExpressBladeId($thisRecord->id)->delete();
        return response()->json(['level'=>'success','message'=>'删除成功','data'=>[]]);
    }


    public function setReturnAddress(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $name   =$request->get('name');
        $phone  =$request->get('phone');
        $address=$request->get('address');
        $remark =$request->get('remark');
        $record=ReturnAddress::first();
        if (!$record)
            $record=new ReturnAddress();
        $record->name=$name ? $name : '';
        $record->phone=$phone ? $phone : '';
        $record->address=$address ? $address : '';
        $record->remark=$remark ? $remark : '';
        $record->save();
        return response()->json(['level'=>'success','message'=>'保存成功']);
    }

    public function setShop(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name      = $request->get('name');
        $contact   = $request->get('contact');
        $province  = $request->get('province');
        $city      = $request->get('city');
        $area      = $request->get('area');
        $address   = $request->get('address');
        $sort      = $request->get('sort');
        $thumbId   = $request->get('thumb_id');
        $id        = !is_null($request->get('id'))?$request->get('id'):0;

        $addressDetail = $province.$city.$area.$address;

        $addressResult = BusinessLicense::searchFeedService($addressDetail);

        $thatShop = Shops::whereId(trim($id))->first();

        if(!$thatShop)
            $thatShop = new Shops();

        if(!is_null($name))$thatShop->name               = $name;
        if(!is_null($contact))$thatShop->contact         = $contact;
        if(!is_null($sort))$thatShop->sort               = $sort;
        if(!is_null($thumbId))$thatShop->thumb_id        = $thumbId;
        if(!is_null($province))$thatShop->province       = $province;
        if(!is_null($city))$thatShop->city               = $city;
        if(!is_null($area))$thatShop->area               = $area;
        if(!is_null($address))$thatShop->address         = $address;
        $thatShop->lng                      = !empty($addressResult) && $addressResult->status == 0 ? $addressResult->result->location->lng : 0;
        $thatShop->lat                      = !empty($addressResult) && $addressResult->status == 0 ? $addressResult->result->location->lat : 0;
        $thatShop->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatShop]);
    }

    public function delShop(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))? $request->get('id'):0;

        /** @var Shops $thatShop */
        $thatShop = Shops::whereId($id)->first();

        if(!$thatShop)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatShop->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatShop]);
    }
}